# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext, Context, loader
from manabu55app.models import Addr
from google.appengine.ext import ndb


def list(request):

	qry = Addr.query().order(Addr.created)
	addrs = qry.fetch()
	count = Addr.query().count()

	return render_to_response('list.html', {
		'addrs': addrs,
		'count': count,
	}, context_instance=RequestContext(request))


def add(request):

	if request.method == 'POST':
		
		name = request.POST.get('name1', '')
		address = request.POST.get('address', '')
		tel = request.POST.get('tel', '')

		addr = Addr(
			name = name,
			address = address,
			tel = tel,
		)
		addr.put()

		return redirect("/")
	
	else:

		return render_to_response('add.html', {

		}, context_instance=RequestContext(request))


def edit(request, id):

	if request.method == 'POST':

		addr = ndb.Key(Addr, int(id)).get()

		name = request.POST.get('name1', '')
		address = request.POST.get('address', '')
		tel = request.POST.get('tel', '')

		addr.name = name
		addr.address = address
		addr.tel = tel

		addr.put()

		return redirect("/")
	
	else:

		addr = ndb.Key(Addr, int(id)).get()

		return render_to_response('edit.html', {
			'addr': addr,
		}, context_instance=RequestContext(request))


def delete(request, id):

	addr_key = ndb.Key(Addr, int(id))
	addr_key.delete()

	return render_to_response('delete.html', {

	}, context_instance=RequestContext(request))


def view(request, id):

	key = ndb.Key(Addr, int(id))
	addr = key.get()

	return render_to_response('view.html', {
		'addr':addr,
	}, context_instance=RequestContext(request))

